package com.janko.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author nyk
 * @Date 2021/3/30 11:38
 * @Version 1.0
 * @Desc 设置网关的访问类
 */
public class AccessFilter extends ZuulFilter {

    /**
     * 定义拦截类型 4中类型
     */
    @Override
    public String filterType() {
//        public static final String ERROR_TYPE = "error";
//        public static final String POST_TYPE = "post";
//        public static final String PRE_TYPE = "pre";
//        public static final String ROUTE_TYPE = "route";
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 	标识拦截器的状态使用 值越小，越在前
     */
    @Override
    public int filterOrder() {
        return 10;
    }


    /**
     * 该过滤器是否生效
     */
    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();


        String uri = request.getRequestURI();
        System.out.println("来源uri："+uri);
        //只有此接口/api-passenger/api-passenger-gateway-test/hello才被拦截
        String checkUri = "/api-passenger/api-passenger-gateway-test/hello";
        if(checkUri.equalsIgnoreCase(uri)) {
            return true;
        }
//		 测试路径
        if(uri.contains("api-driver")) {
            return true;
        }

        return false;
    }

    /**
     * 拦截后的具体业务逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        System.out.println("auth 拦截");
        //获取上下文（重要，贯穿 所有filter，包含所有参数）
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String token = request.getHeader("Authorization");
        if(StringUtils.isNotBlank(token)){
            /**
             * 走token的校验真伪业务
             */
        }

        // 不往下走，还走剩下的过滤器，但是不向后面的服务转发。
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        requestContext.setResponseBody("auth fail");

        return null;
    }
}
